package com.leetcode.sorts.linked;

import com.leetcode.problems_05.ListNode;

/**
 * @Author: WuPeng
 * @Date: 2021/5/22 7:47 下午
 *
 * 203: 移除链表元素
 * 给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点 。
 *
 * 示例 1：
 *      输入：head = [1,2,6,3,4,5,6], val = 6
 *      输出：[1,2,3,4,5]
 *
 * 示例 2：
 *      输入：head = [], val = 1
 *      输出：[]
 *
 * 示例 3：
 *      输入：head = [7,7,7,7], val = 7
 *      输出：[]
 *
 */
class RemoveElements_203 {

    public static ListNode removeElements(ListNode head, int val){

        ListNode tmp_head = new ListNode(-1);
        tmp_head.next = head;
        ListNode curr_node = tmp_head;

        while (curr_node.next != null){
            if (curr_node.next.val == val){
                curr_node.next = curr_node.next.next;
            }
            else {
                curr_node = curr_node.next;
            }
        }
        return tmp_head.next;
    }

    public static void main(String[] args) {
        ListNode head  = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        ListNode node5 = new ListNode(6);

        head.next  = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode new_head = removeElements(head, 3);

        while (new_head != null){
            System.out.print(new_head.val + ",");
            new_head = new_head.next;
        }
    }

}
